package com.nny.alarm.data;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

public class DataProvider extends ContentProvider
{

	public static final String URI_AUTHOR 		= "com.uxwine.db";
	private static final int CODE_ALARM_DIR 	= 1;
	private static final int CODE_ALARM_ITEMS	= 2;
	private static final UriMatcher MATCHER 	= new UriMatcher(UriMatcher.NO_MATCH);
	
	private DBAlarm mdbAlarm;
	
	static 
	{
		MATCHER.addURI(URI_AUTHOR, TBAlram.MATCH_DIR, CODE_ALARM_DIR);
		MATCHER.addURI(URI_AUTHOR, TBAlram.MATCH_ITEMS, CODE_ALARM_ITEMS);
	}
	
	
	@Override
	public boolean onCreate()
	{
		mdbAlarm = new DBAlarm(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder)
	{
		int match = MATCHER.match(uri);
		SQLiteQueryBuilder sqb = new SQLiteQueryBuilder();
		
		switch(match)
		{
		case CODE_ALARM_DIR:
			sqb.setTables(TBAlram.TB_NAME);
			break;
		case CODE_ALARM_ITEMS:
			sqb.setTables(TBAlram.TB_NAME);
			sqb.appendWhere(TBAlram.Columns._ID + "=");
			sqb.appendWhere(uri.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("Unknow uri:" + uri);
		}
		
		SQLiteDatabase db = mdbAlarm.getReadableDatabase();
		Cursor cur = sqb.query(db, 
				projection, 
				selection, 
				selectionArgs, null, null, sortOrder);
		
		if(null != cur)
		{
			cur.setNotificationUri(getContext().getContentResolver(), uri);
		}
		
		return cur;
	}

	@Override
	public String getType(Uri uri)
	{
		int match = MATCHER.match(uri);
		switch(match)
		{
		case CODE_ALARM_DIR:
			return TBAlram.VDN_DIR;
		case CODE_ALARM_ITEMS:
			return TBAlram.VDN_ITEMS;
		default:
			throw new IllegalArgumentException("Unknow uri:" + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values)
	{
		if (MATCHER.match(uri) != CODE_ALARM_DIR)
            throw new IllegalArgumentException("Unknow uri:" + uri);

        ContentValues vs = new ContentValues(values);

        SQLiteDatabase db = mdbAlarm.getWritableDatabase();
        long rowId = db.insert(TBAlram.TB_NAME, TBAlram.Columns.LABEL, vs);
        if (rowId < 0)
            throw new SQLException("Failed to insert row into " + uri);

        Uri newUri = ContentUris.withAppendedId(TBAlram.CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(newUri, null);
        return newUri;
	}

	@Override
	public int delete(Uri uri, String where, String[] args)
	{
		int match = MATCHER.match(uri);		
		SQLiteDatabase db = mdbAlarm.getReadableDatabase();
		int count = 0;
		
		switch(match)
		{
		case CODE_ALARM_DIR:
			count = db.delete(TBAlram.TB_NAME, where, args);
			break;
		case CODE_ALARM_ITEMS:{
			String segment = uri.getPathSegments().get(1);
			long id = Long.parseLong(segment);
			where = BaseColumns._ID + "=" + segment;
			if(!TextUtils.isEmpty(where))
				where = BaseColumns._ID + "=" + segment;
			else
				where = BaseColumns._ID + "=" + segment + " AND (" + where + ")";
			count = db.delete(TBAlram.TB_NAME, where, args);
			break;
		}
		default:
			throw new IllegalArgumentException("Unknow uri:" + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs)
	{
		int count;
        int match = MATCHER.match(uri);
        SQLiteDatabase db = mdbAlarm.getWritableDatabase();
        switch (match) 
        {
            case CODE_ALARM_ITEMS: 
            {
                String segment = uri.getPathSegments().get(1);
                long id = Long.parseLong(segment);
                count = db.update(TBAlram.TB_NAME, values, BaseColumns._ID +"="+ id, null);
                break;
            }
            default: 
            {
                throw new UnsupportedOperationException("Cannot update URL: " + uri);
            }
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	
	static String buildContentUri(String name)
	{		
		StringBuffer sb = new StringBuffer("content://");
		sb.append(URI_AUTHOR).append("/").append(name);
		return sb.toString();
	}
	
	static int deleteAt(SQLiteDatabase db, String dbName, Uri uri,  String where, String[] args)
	{
		String id = uri.getPathSegments().get(1);
		if(!TextUtils.isEmpty(where))
			where = BaseColumns._ID + "=" + id;
		else
			where = BaseColumns._ID + "=" + id + " AND (" + where + ")";
		return db.delete(dbName, where, args);
	}
}
